const BASE_URL = 'http://localhost:8090';

import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ErrorCode } from '../enums/ErrorCode';

export const getAuthHeader = () => {
  const token = localStorage.getItem('token');
  return token ? { Authorization: token } : {};
};

export const logout = (router) => {
  localStorage.removeItem('token');
  delete axios.defaults.headers.common['Authorization'];
  router.push({ name: 'auth' });
};

export const loginByPassword = (email, password) => {
  return axios.post(`${BASE_URL}/users/loginByPassword`, {
    email,
    password
  });
};

export const sendVerificationCodeAPI = (email) => {
  return axios.post(`${BASE_URL}/users/sendVerificationCode`, null, {
    params: { email }
  });
};

export const registerAndHandleResponse = async (email, password, verificationCode, clearInputs, triggerLoginSwitch) => {
  try {
    const response = await axios.post(`${BASE_URL}/users/register`, {
      email,
      password,
      verificationCode
    });
    const { code, info } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('注册成功');
      clearInputs();
      triggerLoginSwitch();
    } else if (code === ErrorCode.USER_EXIST.code) {
      ElMessage.error('用户已存在');
      clearInputs();
      triggerLoginSwitch();
    } else if (code === ErrorCode.VERIFICATION_CODE_ERROR.code) {
      ElMessage.error('验证码不存在');
    } else {
      ElMessage.error('注册失败');
    }
  } catch (error) {
    console.error('注册失败', error);
    ElMessage.error('注册失败');
  }
};

export const loginAPI = async (email, password, router) => {
  try {
    const response = await loginByPassword(email, password);
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('登录成功');
      localStorage.setItem('token', data);
      axios.defaults.headers.common['Authorization'] = data;
      router.push('/');
    } else {
      ElMessage.error('登录失败');
    }
  } catch (error) {
    console.error('登录失败', error);
    ElMessage.error('登录失败');
  }
};

export const goToLogin = (router) => {
  if (!router || typeof router.push !== 'function') {
    console.error('无效的 router 对象');
    return;
  }
  ElMessage.error('未找到 Authorization，请重新登录');
  localStorage.removeItem('token');
  delete axios.defaults.headers.common['Authorization'];
  router.push('/auth');
};

export const sendVerificationCodeByUpdatePasswordAPI = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.post('http://localhost:8090/users/getUserEmailAndSendVerificationCode', {}, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('验证码发送成功');
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '验证码发送失败');
    }
  } catch (error) {
    console.error('验证码发送失败', error);
    ElMessage.error('验证码发送失败');
  }
};

export const getDataSummary = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get('http://localhost:8090/userBehavior/dataSummary', {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取数据摘要失败');
    }
  } catch (error) {
    console.error('获取数据摘要失败', error);
    ElMessage.error('获取数据摘要失败');
  }
};

export const getUserClusterFeatures = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/userClusterFeatures`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取用户聚类特征失败');
    }
  } catch (error) {
    console.error('获取用户聚类特征失败', error);
    ElMessage.error('获取用户聚类特征失败');
  }
};

export const getArpuDaily = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/arpuDaily`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取 ARPU 日数据失败');
    }
  } catch (error) {
    console.error('获取 ARPU 日数据失败', error);
    ElMessage.error('获取 ARPU 日数据失败');
  }
};

export const getArppuDaily = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/arppuDaily`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取 ARPPU 日数据失败');
    }
  } catch (error) {
    console.error('获取 ARPPU 日数据失败', error);
    ElMessage.error('获取 ARPPU 日数据失败');
  }
};

export const getOrderRateDaily = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/orderRateDaily`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取订单转化率日数据失败');
    }
  } catch (error) {
    console.error('获取订单转化率日数据失败', error);
    ElMessage.error('获取订单转化率日数据失败');
  }
};

export const getRepeatBuyCycle = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/repeatBuyCycle`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取复购周期数据失败');
    }
  } catch (error) {
    console.error('获取复购周期数据失败', error);
    ElMessage.error('获取复购周期数据失败');
  }
};

export const getRepeatBuyRatio = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/repeatBuyRatio`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取复购率数据失败');
    }
  } catch (error) {
    console.error('获取复购率数据失败', error);
    ElMessage.error('获取复购率数据失败');
  }
};

export const getConversionPercentage = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/conversionPercentage`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取转化率数据失败');
    }
  } catch (error) {
    console.error('获取转化率数据失败', error);
    ElMessage.error('获取转化率数据失败');
  }
};

export const getConversionPercentage1212 = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/conversionPercentage1212`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取转化率数据失败');
    }
  } catch (error) {
    console.error('获取转化率数据失败', error);
    ElMessage.error('获取转化率数据失败');
  }
};

export const getPathConversionRate = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/PathConversionRate`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取路径转化率数据失败');
    }
  } catch (error) {
    console.error('获取路径转化率数据失败', error);
    ElMessage.error('获取路径转化率数据失败');
  }
};

export const getPathConversionRate1212 = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/PathConversionRate1212`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取路径转化率数据失败');
    }
  } catch (error) {
    console.error('获取路径转化率数据失败', error);
    ElMessage.error('获取路径转化率数据失败');
  }
};

export const getBehaviorTypeWithHour = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/behaviorTypeWithHour`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取行为类型数据失败');
    }
  } catch (error) {
    console.error('获取行为类型数据失败', error);
    ElMessage.error('获取行为类型数据失败');
  }
};

export const getBehaviorTypeWithHour1212 = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/behaviorTypeWithHour1212`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取行为类型数据失败');
    }
  } catch (error) {
    console.error('获取行为类型数据失败', error);
    ElMessage.error('获取行为类型数据失败');
  }
};

export const getPvHourly = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/pvHourly`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取每小时 PV 数据失败');
    }
  } catch (error) {
    console.error('获取每小时 PV 数据失败', error);
    ElMessage.error('获取每小时 PV 数据失败');
  }
};

export const getPvHourly1212 = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/pvHourly1212`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取双十二每小时 PV 数据失败');
    }
  } catch (error) {
    console.error('获取双十二每小时 PV 数据失败', error);
    ElMessage.error('获取双十二每小时 PV 数据失败');
  }
};

export const getUvHourly = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/uvHourly`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取每小时 UV 数据失败');
    }
  } catch (error) {
    console.error('获取每小时 UV 数据失败', error);
    ElMessage.error('获取每小时 UV 数据失败');
  }
};

export const getUvHourly1212 = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/uvHourly1212`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取双十二每小时 UV 数据失败');
    }
  } catch (error) {
    console.error('获取双十二每小时 UV 数据失败', error);
    ElMessage.error('获取双十二每小时 UV 数据失败');
  }
};

export const getPvDaily = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/pvDaily`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取日 PV 数据失败');
    }
  } catch (error) {
    console.error('获取日 PV 数据失败', error);
    ElMessage.error('获取日 PV 数据失败');
  }
};

export const getUvDaily = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/uvDaily`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取日 UV 数据失败');
    }
  } catch (error) {
    console.error('获取日 UV 数据失败', error);
    ElMessage.error('获取日 UV 数据失败');
  }
};

export const getUserBehaviorDistribution = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/userBehaviorDistribution`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取用户行为分布数据失败');
    }
  } catch (error) {
    console.error('获取用户行为分布数据失败', error);
    ElMessage.error('获取用户行为分布数据失败');
  }
};

export const getTop50UserBuyCount = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/top50UserBuyCount`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取用户购买次数 Top 50 数据失败');
    }
  } catch (error) {
    console.error('获取用户购买次数 Top 50 数据失败', error);
    ElMessage.error('获取用户购买次数 Top 50 数据失败');
  }
};

export const getAllUserBuyCount = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.get(`${BASE_URL}/userBehavior/userBuyCount`, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取用户购买次数数据失败');
    }
  } catch (error) {
    console.error('获取用户购买次数数据失败', error);
    ElMessage.error('获取用户购买次数数据失败');
  }
};

export const getUserInfo = async (router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.post(`${BASE_URL}/users/getUserInfo`, null, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      switch (data.userStatus) {
        case '0':
          data.userStatus = '正常';
          break;
        case '1':
          data.userStatus = '异常';
          break;
        case '3':
          data.userStatus = '冻结';
          break;
        default:
          data.userStatus = '未知';
      }
      return data;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else {
      ElMessage.error(info || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败', error);
    ElMessage.error('获取用户信息失败');
  }
};

export const updateUserPassword = async (email, password, verificationCode, router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }
  try {
    const response = await axios.post(`${BASE_URL}/users/updateUserPassword`, {
      email,
      password,
      verificationCode
    }, {
      headers
    });
    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('密码修改成功');
      return true;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else if (code === ErrorCode.VERIFICATION_CODE_ERROR.code) {
      ElMessage.error('验证码错误');
    } else if (code === ErrorCode.ILLEGAL_PARAMETER.code) {
      ElMessage.error('参数错误');
    } else if (code === ErrorCode.USER_NOT_EXIST.code) {
      ElMessage.error('用户不存在');
    } else {
      ElMessage.error(info || '密码修改失败');
    }
    return false;
  } catch (error) {
    console.error('密码修改失败', error);
    ElMessage.error('密码修改失败');
    return false;
  }
};

export const updateUserAvatar = async (file, router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', file);

    const response = await axios.post(`${BASE_URL}/users/updateUserAvatar`, formData, {
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data'
      }
    });

    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('头像更新成功');
      return true;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else if (code === ErrorCode.USER_NOT_EXIST.code) {
      ElMessage.error('用户不存在');
    } else if (code === ErrorCode.ILLEGAL_PARAMETER.code) {
      ElMessage.error('非法参数');
    } else {
      ElMessage.error(info || '头像更新失败');
    }
    return false;
  } catch (error) {
    console.error('头像更新失败', error);
    ElMessage.error('头像更新失败');
    return false;
  }
};

export const updateUserInfo = async (nickname, biography, router) => {
  const headers = getAuthHeader();
  if (!headers.Authorization) {
    goToLogin(router);
    return;
  }

  try {
    const response = await axios.post(`${BASE_URL}/users/updateUserInfo`, {
      nikeName: nickname,
      biography
    }, {
      headers
    });

    const { code, info, data } = response.data;
    if (code === ErrorCode.SUCCESS.code) {
      ElMessage.success('个人信息更新成功');
      return true;
    } else if (code === ErrorCode.TOKEN_ERROR.code) {
      goToLogin(router);
    } else if (code === ErrorCode.USER_NOT_EXIST.code) {
      ElMessage.error('用户不存在');
    } else if (code === ErrorCode.ILLEGAL_PARAMETER.code) {
      ElMessage.error('非法参数');
    } else {
      ElMessage.error(info || '个人信息更新失败');
    }
    return false;
  } catch (error) {
    console.error('个人信息更新失败', error);
    ElMessage.error('个人信息更新失败');
    return false;
  }
};


